﻿CREATE PROCEDURE [ServiceEngine].[CreateChannel]
	@Name nvarchar(400),
	@BindingID uniqueidentifier,
	@MonikerSchema xml,
	@EditorAssembly nvarchar(max),
	@EditorTypeName nvarchar(max),
	@Description ntext = null,
	@ID uniqueidentifier OUTPUT
AS
BEGIN
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	SET NOCOUNT ON;

	IF @ID IS NULL 
		SET @ID = newid();

	BEGIN TRY
		BEGIN TRANSACTION

		INSERT INTO ServiceEngine.Channels (ChannelID, MonikerSchema, BindingID, EditorAssembly, EditorTypeName)
		VALUES (@ID, @MonikerSchema, @BindingID, @EditorAssembly, @EditorTypeName)

		BEGIN TRY
			INSERT INTO ServiceEngine.Names (EntityID, EntityTypeID, EntityName, EntityDescription)
			VALUES (@ID, 7, @Name, @Description)
		END TRY
		BEGIN CATCH

			SELECT 
				@ErrorMessage = 'Attempt to insert ChannelType with duplicate name failed',
				@ErrorSeverity = 11,
				@ErrorState = ERROR_STATE();

			RAISERROR (@ErrorMessage, 
					   @ErrorSeverity,
					   1);
		END CATCH

		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();

		IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;

		RAISERROR (@ErrorMessage, 
				   @ErrorSeverity,
				   1);
	END CATCH
END